package com.lambkit.module.cms.web.directive;

import com.jfinal.kit.StrKit;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import com.lambkit.module.cms.rpc.model.CmsArticle;
import com.lambkit.module.cms.rpc.model.CmsTag;
import com.lambkit.web.directive.LambkitDirective;
import com.lambkit.web.directive.annotation.JFinalDirective;

import java.util.List;

/**
 * @author Henry Yang 杨勇 (gismail@foxmail.com)
 * @version 1.0
 * @Package com.lambkit.module.cms.web.directive
 */
@JFinalDirective("tagArticles")
public class TagArticlesDirective extends LambkitDirective {

    @Override
    public void onRender(Env env, Scope scope, Writer writer) {

        String tag = getPara("tag", scope);

        if (StrKit.isBlank(tag)) {
            throw new IllegalArgumentException("#tagArticles() args is error, tag must not be empty." + getLocation());
        }

        //Boolean hasThumbnail = getParaToBool("hasThumbnail", scope);
        String orderBy = getPara("orderBy", scope, "order_number desc,id desc");
        int count = getParaToInt("count", scope, 10);

        CmsTag cmsTag = CmsTag.service().findFirstByAlias(tag);
        if (cmsTag == null) {
            return;
        }

        scope.setLocal("tag", cmsTag);

        List<CmsArticle> articles = CmsArticle.service().findListByTagId(cmsTag.getTagId(), orderBy, count);

        if (articles == null || articles.isEmpty()) {
            return;
        }

        scope.setLocal("articles", articles);
        renderBody(env, scope, writer);
    }


    @Override
    public boolean hasEnd() {
        return true;
    }
}
